<script setup>
import { reactive, ref, watch } from 'vue'
import ShortDatedSaleDialog from '@/pages/ShortDatedSale/components/ShortDatedSaleDialog.vue'
import { deleteShortDatedProductById, listShortDatedProduct } from '@/service/shortDatedProduct.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryProductEcho } from '@/service/product.js'
// 商品列表
const productList = ref([])
const searchForm = reactive({
  productName: '',
  currentPage: 1,
  pageSize: 10,
})
const type = ref('add')
const shortDatedSaleDialogRef = ref()
const totalRecords = ref(0)
function clearQueryParam() {
  if (searchForm.productName === '' && searchForm.currentPage === 1 && searchForm.pageSize === 10) {
    loadData()
  } else {
    Object.assign(searchForm, {
      productName: '',
      currentPage: 1,
      pageSize: 10,
    })
  }
}
function addNewDatedProduct() {
  type.value = 'add'
  shortDatedSaleDialogRef.value.showModal = true
}

watch(
  searchForm,
  () => {
    loadData()
  },
  { immediate: true }
)

async function loadData() {
  const { data } = await listShortDatedProduct(searchForm.productName, searchForm.currentPage, searchForm.pageSize)
  totalRecords.value = data.total
  productList.value = data.records
  console.log(productList)
}

async function onTapEditButton(row) {
  type.value = 'edit'
  const productId = row.productId
  const res = await queryProductEcho(productId)
  shortDatedSaleDialogRef.value.dialogForm.productInfo = res.data
  shortDatedSaleDialogRef.value.dialogForm.manufacturingDate = res.data.manufacturingDate
    ? new Date(res.data.manufacturingDate)
    : null
  shortDatedSaleDialogRef.value.dialogForm.expiryDate = res.data.expiryDate ? new Date(res.data.expiryDate) : null
  shortDatedSaleDialogRef.value.showModal = true
}
function onTapDeleteButton(row) {
  console.log(row)
  ElMessageBox.confirm(`确定删除临期特惠商品：<span style="color: red">${row.productName}</span>?`, '信息', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true, // 允许内容使用 HTML 字符串
  })
    .then(async () => {
      await deleteShortDatedProductById(row.productId)
      ElMessage({
        type: 'success',
        message: '成功删除临期特惠商品！此操作将会使该商品变为下架状态',
      })
      await loadData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
</script>

<template>
  <div class="short-dated-sale">
    <el-collapse expand-icon-position="left">
      <el-collapse-item title="操作提示">
        <div class="tip">* 临期特惠商品在活动时间内，只要库存充足、未下架，符合购买条件就能下单购买。</div>
        <div class="tip">* 临期特惠商品已下架，不能继续下单购买，已下单的商品在配送时效内正常配送。</div>
        <div class="tip">* 临期特惠商品已售罄，不能继续下单购买。</div>
      </el-collapse-item>
    </el-collapse>
    <el-form :model="searchForm" inline label-position="right" label-width="auto" style="margin-top: 10px">
      <el-form-item label="商品名称:" style="width: 100%">
        <div style="display: flex; align-items: center; width: 100%">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" style="width: 300px"></el-input>
          <el-button style="margin-left: 10px" type="info" @click="clearQueryParam">清空查询</el-button>
          <el-button style="margin-left: auto" type="primary" @click="addNewDatedProduct">新增临期商品</el-button>
        </div>
      </el-form-item>
    </el-form>
    <el-table
      :data="productList"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      border
      style="width: 100%"
    >
      <el-table-column header-align="center" label="商品信息" width="300">
        <template #default="scope">
          <div class="product-info">
            <img :src="scope.row.imageUrl" alt="" />
            <div class="product-name">{{ scope.row.productName }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品价格" width="120">
        <template #default="scope">
          <span style="font-size: 12px" v-if="scope.row.minPrice === scope.row.maxPrice">
            ￥{{ scope.row.minPrice }}
          </span>
          <span style="font-size: 12px" v-else> ￥{{ scope.row.minPrice }} ~ ￥{{ scope.row.maxPrice }} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="优惠价格" width="120">
        <template #default="scope">
          <span style="font-size: 12px" v-if="scope.row.minPromotionPrice === scope.row.maxPromotionPrice">
            ￥{{ scope.row.maxPromotionPrice }}
          </span>
          <span style="font-size: 12px" v-else>
            ￥{{ scope.row.minPromotionPrice }} ~ ￥{{ scope.row.maxPromotionPrice }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="库存信息" width="120">
        <template #default="scope">
          <div class="product-stock">
            <div class="available-stock">可用库存:{{ scope.row.availableStock }}</div>
            <div class="total-stock">总库存:{{ scope.row.stock }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="200">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品生产日期" width="120">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.manufacturingDate }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品有效期" width="120">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.expiryDate }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="200">
        <template #default="scope">
          <el-button type="primary" @click="onTapEditButton(scope.row)">编辑</el-button>
          <el-button type="danger" @click="onTapDeleteButton(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="searchForm.currentPage"
      v-model:page-size="searchForm.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :total="totalRecords"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 10px"
    />
  </div>
  <short-dated-sale-dialog ref="shortDatedSaleDialogRef" :type="type" @update="loadData" />
</template>

<style lang="scss" scoped>
.short-dated-sale {
  background: #fff;
  padding: 20px;
}
:deep(.el-collapse-item__content) {
  padding: 10px;
}
.product-info {
  display: flex;
  align-items: center;
  img {
    width: 60px;
    height: 60px;
  }
  .product-name {
    margin-left: 10px;
    font-size: 12px;
    text-align: left;
    line-height: 15px;
  }
}
.product-stock {
  font-size: 12px;
  display: flex;
  flex-direction: column;
}
</style>
